<?php
/**
 * Class that handels all database related actions.
 */
class Database {
	
	var $link;
	
	/**
	 * Connects the instance of this object to the selected database.
	 * @param $database The name of the database to connect to.
	 */
	function Database($database="@database.name@") {
		
		$this->link = mysql_connect("@database.server@", "@database.userName@", "@database.password@") or die("Could not connect to server: " . mysql_error());
		mysql_select_db($database) or die("Could not select database.");
	}
	
	/**
	 * Destroys a database connection.
	 * @param $link The connection to kill.
	 */
	function disconnect() {
		mysql_close($this->link);
	}
	
	/**
	 * Executes a single query.
	 * @param $query The query to execute.
	 * @return The result of the select query.
	 */
	function execute($query) { 
		
		$result = mysql_query($query, $this->link) or die("Query failed: " . mysql_error());
		return $result;
	}
	
	/**
	 * Inserts a new record into a table and returns the LAST_INSERT_ID() of the new record.
	 * @param $query The query to execute.
	 * @return The LAST_INSERT_ID() of the inserted row.
	 */
	function insert($query) {
		
		$this->execute("START TRANSACTION");
		$this->execute($query);
		$result = $this->execute("SELECT LAST_INSERT_ID() as rowID");
		$this->execute("COMMIT");
		
		$row = mysql_fetch_assoc($result);
		
		return $row["rowID"];
	}
	
	/**
	 * Executes an list of queries as a single transaction.
	 * @param $queries The list queries to execute.
	 * @return The result of the last select query.
	 */
	function transaction($queries) {
		
		$result = null;
		
		$this->execute("START TRANSACTION");
		for ($i = 0; $i < sizeof($queries); $i++) {
			$result = $this->execute($queries[$i]);
		}
		$this->execute("COMMIT");
		
		return $result;
	}
}
?>